package com.ccc.controller;


import com.ccc.entity.LoginUser;
import com.ccc.mapper.UserInfoMapper;
import com.ccc.service.IUserInfoService;
import com.ccc.utils.JwtUtil;
import com.ccc.utils.RedisCache;
import com.ccc.utils.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ccc
 * @since 2021-12-26
 */
@Controller
public class UserInfoController {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    IUserInfoService userInfoService;

    @Autowired
    RedisCache redisCache;

    /**
     * 教师获取学生详情信息
     *
     * @return
     */
    @GetMapping("/teacher/stuinfo")
    @PreAuthorize("hasAuthority('teacher')")
    @ResponseBody
    public ResponseResult stuInfos() {
        return new ResponseResult(200, "success", userInfoMapper.getStuInfo());
    }

    /**
     * 用户获取自己个人的详情信息
     *
     * @param request
     * @return
     */
    @GetMapping("/user/info")
    @PreAuthorize("hasAnyAuthority('student','teacher')")
    @ResponseBody
    public ResponseResult GetstuInfoByKey(HttpServletRequest request) {

        String token = request.getHeader("token");
        if (!StringUtils.hasText(token) || token.equals("null")) {
            return new ResponseResult(400, "token错误！");
        }

        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token错误！");
        }

//         从redis中获取用户信息
//        String redisKey = "Login:" + username;
//        LoginUser loginUser = redisCache.getCacheObject(redisKey);

        return new ResponseResult(200, "success", userInfoMapper.getInfoById(username));
    }

}
